package com.gewei.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.gewei.pojo.Permission;
import com.gewei.pojo.Role;
import com.gewei.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 认证和授权
 */
//@Component
public class SpringSecurityUserService implements UserDetailsService {

    /**
     * 使用 Dubbo 远程调用 health_service_provider 获取数据库中的用户信息
     */
    @Reference
    private UserService userService;

    /**
     * 根据用户名查询数据库获取用户信息
     *
     * @param username 用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.findByUsername(username);
        //  用户名不存在
        if (user == null) {
            return null;
        }
        //  动态为当前用户授权
        List<GrantedAuthority> list = new ArrayList<>();
        //  用户的角色信息
        Set<Role> roles = user.getRoles();
        //  遍历角色集合
        for (Role role : roles) {
            //  为用户授予角色
            list.add(new SimpleGrantedAuthority(role.getKeyword()));
            //  角色的权限信息
            Set<Permission> permissions = role.getPermissions();
            //  遍历权限集合
            for (Permission permission : permissions) {
                //  为用户授权
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }

        //  用户名、密码（已经加密）、权限集合
        org.springframework.security.core.userdetails.User securityUser =
                new org.springframework.security.core.userdetails.User(
                        username, user.getPassword(), list);

        return securityUser;
    }
}